package com.nanako.common;

import com.nanako.exception.CascadingDeleteException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

@Slf4j
@RestControllerAdvice(annotations = {RestController.class, Controller.class})
public class GlobalExceptionHandler {

    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R repeatEmpException(SQLIntegrityConstraintViolationException exception) {
        // 1、打印异常信息 log.error()  getMessage
        // 2、获取异常信息 getMessage()  Duplicate entry '111' for key 'idx_username'
        String message = exception.getMessage();
        log.error("异常信息" + message);
        // 3、判断异常信息是唯一约束异常  contains("Duplicate entry")
        log.error("异常原因" + exception.getCause());
        if(message.contains("Duplicate entry")){//违反的是唯一约束
            //3.1、如果是，获取异常信息中的用户名 split  replace ，返回 xxx已存在
            String error = message.split(" ")[2].split("'")[1];
            return R.error(error + "已存在");
        }
        //3.2、如果不是，返回 “数据异常！！”
        return R.error("数据异常");
    }

    @ExceptionHandler(CascadingDeleteException.class)
    public R cascadingDelete(CascadingDeleteException exception) {
        log.error(exception.getMessage());
        log.error(exception.getCause() + "");
        return R.error(exception.getMessage());
    }
}
